package com.huisang.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huisang.springboot.controller.dto.UserDTO;
import com.huisang.springboot.entity.User;
import com.huisang.springboot.exception.ServiceException;
import com.huisang.springboot.mapper.UserMapper;
import com.huisang.springboot.service.UserService;
import com.huisang.springboot.utils.Code;
import com.huisang.springboot.utils.Result;
import com.huisang.springboot.utils.TokenUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public User getUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        List<User> list = list(queryWrapper);

        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public User getUserById(Integer id) {
        return getById(id);
    }

    @Override
    public Result<UserDTO> login(UserDTO userDTO) {
        Result<UserDTO> result = new Result<>();
        try {
            if(StrUtil.isBlank(userDTO.getUsername())) {
                result.setMessage("用户名为空！");
                return result;
            }
            if (StrUtil.isBlank(userDTO.getPassword())) {
                result.setMessage("密码为空！");
                return result;
            }
            //根据用户名查找用户
            User selectUser = getUserByName(userDTO.getUsername());
            if(selectUser != null && selectUser.getPassword().equals(userDTO.getPassword())) {
                BeanUtil.copyProperties(selectUser, userDTO, true);
                result.setCode(Code.success);
                result.setMessage("登录成功！");
                userDTO.setToken(TokenUtil.getToken(selectUser.getId().toString(), selectUser.getPassword()));
                result.setData(userDTO);
                return result;
            }
            result.setCode(Code.service_error);
            result.setMessage("用户名或密码不正确！");

            return result;
        } catch (Exception e) {
            throw new ServiceException(Code.error, "系统错误");
        }

    }

    @Override
    public Result<Boolean> insertUser(User user) {
        Result<Boolean> result = new Result<>();
        User selectUser = getUserByName(user.getUsername());
        if(selectUser != null) {
            result.setCode(Code.service_error);
            result.setMessage("用户名重复");
            result.setData(false);
            return result;
        }
        boolean i = save(user);
        if(i) {
            result.setCode(Code.success);
            result.setMessage("添加成功！");
            result.setData(i);
        }else {
            result.setCode(Code.error);
            result.setMessage("添加失败！");
            result.setData(i);
        }
        return result;
    }

    @Override
    public Result<Boolean> deleteUser(Integer id) {
        Result<Boolean> result = new Result<>();
        boolean i = removeById(id);
        if(i) {
            result.setCode(Code.success);
            result.setMessage("删除成功！");
            result.setData(i);
        }else {
            result.setCode(Code.error);
            result.setMessage("删除失败！");
            result.setData(i);
        }
        return result;
    }

    @Override
    public Result<Boolean> deleteBatchUser(List<Integer> ids) {
        Result<Boolean> result = new Result<>();
        boolean i = removeByIds(ids);
        if(i) {
            result.setCode(Code.success);
            result.setMessage("批量删除成功！");
            result.setData(i);
        }else {
            result.setCode(Code.error);
            result.setMessage("批量删除失败！");
            result.setData(i);
        }
        return result;
    }

    @Override
    public Result<Boolean> updateUser(User user) {
        Result<Boolean> result = new Result<>();
        boolean i = updateById(user);
        if(i) {
            result.setCode(Code.success);
            result.setMessage("修改成功！");
            result.setData(i);
        }else {
            result.setCode(Code.error);
            result.setMessage("修改失败！");
            result.setData(i);
        }
        return result;
    }

    @Override
    public Result<List<User>> getUserList() {
        Result<List<User>> result = new Result<>();
        try {
            List<User> userList = list();
            result.setCode(Code.success);
            result.setMessage("查询成功！");
            result.setData(userList);
        } catch (Exception e) {
            result.setCode(Code.error);
            result.setMessage("查询失败！");
        } finally {
            return result;
        }
    }

//    @Override
//    public Result<Map<String, Object>> getUserPageList(Integer pageNum, Integer pageSize) {
//        pageNum = (pageNum - 1) * pageSize;
//        Result<Map<String, Object>> result = new Result<>();
//        try {
//            List<User> userList = userMapper.getUserPageList(pageNum, pageSize);
//            int total = userMapper.selectTotal();
//            Map<String, Object> map = new HashMap<>();
//            map.put("list", userList);
//            map.put("total", total);
//            result.setCode(Code.success);
//            result.setMessage("查询成功！");
//            result.setData(map);
//        } catch (Exception e) {
//            result.setCode(Code.error);
//            result.setMessage("查询失败！");
//        } finally {
//            return result;
//        }
//    }

    @Override
    public Result<IPage<User>> getUserPageList(Integer pageNum, Integer pageSize, String username) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Result<IPage<User>> result = new Result<>();
        try {
            queryWrapper.like(username!=null, "username", username);
            queryWrapper.orderByDesc("id");
            IPage<User> userIPage = page(page, queryWrapper);
            result.setCode(Code.success);
            result.setMessage("查询成功！");
            result.setData(userIPage);
        } catch (Exception e) {
            result.setCode(Code.error);
            result.setMessage("查询失败！");
        } finally {
            return result;
        }
    }

    @Override
    public void export(ServletOutputStream outputStream) {
        ExcelWriter writer = null;
        try {
            List<User> list = list();
            for (User user : list) {
                user.setPassword("不显示隐私数据");
            }
            writer = ExcelUtil.getWriter(true);

            writer.setOnlyAlias(true);

            //一次性写出list内的对象到excel，使用默认样式，强制输出标题
            writer.write(list, true);
            //通过网页输出流输出
            writer.flush(outputStream, true);

        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.close();
        }
    }

    @Override
    public void importEx(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            //这里如果导入的表头是修改过的中文，默认获取的是User类的字段英文，需要再User上注解@Alias
            List<User> users = reader.readAll(User.class);
            QueryWrapper queryWrapper = new QueryWrapper();
            for (User user : users) {
                //每次清空条件
                queryWrapper.clear();
                //重复username判断
                queryWrapper.eq("username", user.getUsername());
                User selectUser = getOne(queryWrapper);
                if(selectUser == null) {
                    save(user);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
